import {
  InputNumber,
  InputNumberProps,
  Select,
  Table,
  TableColumnType,
} from 'antd';
import React from 'react';
import { OptionItem, OptionListProps } from './types';
import { Icon } from '@amcax/base';
export const OptionTable = ({
  data,
  showHeader = false,
  onChange,
}: OptionListProps) => {
  const currentData = React.useMemo(() => [...data], [data]);
  const columns: TableColumnType<OptionItem>[] = [
    {
      title: '名称',
      dataIndex: 'label',
      key: 'label',
      width: 120,
    },
    {
      title: '值',
      dataIndex: 'value',
      key: 'value',
      onCell: (record: OptionItem) => ({
        onClick: (e: React.MouseEvent) => {
          e.stopPropagation();
          if (record.type === 'boolean') {
            const currentRecord = currentData.find(
              (item) => item.key === record.key,
            );
            if (currentRecord) {
              onChange?.(record.key, !currentRecord.value);
            }
          }
        },
      }),
      render: (value, record: OptionItem) => {
        const currentValue = currentData.find(
          (item) => item.key === record.key,
        )?.value;
        const handleChange: InputNumberProps['onChange'] = (val) => {
          onChange?.(record.key, val);
        };
        switch (record.type) {
          case 'number':
            return (
              <InputNumber
                min={0}
                className='w-full'
                defaultValue={value}
                onChange={handleChange}
              />
            );
          case 'boolean':
            return (
              <Icon
                name={`commands/topo/${currentValue ? 'check' : 'close'}`}></Icon>
            );
          case 'select':
            return (
              <Select
                className='w-full'
                defaultValue={value}
                onChange={(val) => onChange?.(record.key, val)}
                options={record.options}
              />
            );
          default:
            return <></>;
        }
      },
    },
  ];
  return (
    <>
      <Table
        style={{ margin: '10px', border: '2px solid #f0f0f0' }}
        columns={columns}
        dataSource={data}
        bordered
        pagination={false}
        size='small'
        showHeader={showHeader}></Table>
    </>
  );
};
